package com.wangfugui.apprentice.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.wangfugui.apprentice.common.util.ResponseUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate template;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.校验请求的控制层映射方法是否包含Token注解
        //1.验证当前的请求是否为映射方法
        if(handler instanceof HandlerMethod){
            //2.强制转换
            HandlerMethod method = (HandlerMethod) handler;
            //3.验证是否包含Token注解
            if(method.hasMethodAnnotation(Token.class)){
                //4.获取令牌
                String token=request.getHeader("TOKEN");
                //5.验证令牌是否有效
                if(template.hasKey("TOKEN:"+token)){
                    //有效 放行
                    return true;
                }
                //拦截 同时返回信息
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSON.toJSONString( ResponseUtils.error("登录过期，请重新登录")));
                return false;
            }
        }
        return true;

    }
}
